package br.com.easyrhour3x.javamail;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;

public class SendMail {

	private String mailSMTPServer;
	private String mailSMTPServerPort;
	public static String EMAIL_FROM;
	public static String EMAIL_SENHA;
   private String email_to = "yoshiharu.takuno@foton.la";

	public SendMail() {
		mailSMTPServer = "smtp.gmail.com";
		mailSMTPServerPort = "465";
	}

	public SendMail(String mailSMTPServer, String mailSMTPServerPort) {
		this.mailSMTPServer = mailSMTPServer;
		this.mailSMTPServerPort = mailSMTPServerPort;
	}

	public void sendMail(String subject, String message) {
		Properties props = new Properties();

		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", mailSMTPServer);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.user", EMAIL_FROM);
		props.put("mail.debug", "true");
		props.put("mail.smtp.port", mailSMTPServerPort);
		props.put("mail.smtp.socketFactory.port", mailSMTPServerPort);
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");

		SimpleAuth auth = null;
		auth = new SimpleAuth(EMAIL_FROM, EMAIL_SENHA);

		Session session = Session.getDefaultInstance(props, auth);
		session.setDebug(true);

		Message msg = new MimeMessage(session);

		try {
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(email_to));
			msg.setFrom(new InternetAddress(EMAIL_FROM));
			msg.setSubject(subject);
			msg.setContent(message, "text/plain");
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Erro ao completar mensagem de email");
			e.printStackTrace();
		}

		Transport tr;
		try {
			tr = session.getTransport("smtp");
			tr.connect(mailSMTPServer, EMAIL_FROM, EMAIL_SENHA);
			msg.saveChanges();
			tr.sendMessage(msg, msg.getAllRecipients());
			tr.close();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Erro ao enviar email");
			e.printStackTrace();
		}

	}
}